package com.ilarele.shopping.client.util;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;

public class DrawableManager {
	@SuppressWarnings("unused")
	private static final String TAG = "DrawableManager";

	public static void fetchView(String picUrl, final View view) {

		if (picUrl == null || picUrl.equals("") || picUrl.equals("null")
				|| view == null)
			return;
		fetchView(picUrl, view, true, 1);
	}

	public static void fetchView(String picUrl, final ImageView view) {
		if (picUrl == null || picUrl.equals("") || picUrl.equals("null")
				|| view == null)
			return;

		fetchView(picUrl, view, true, 1);
	}

	public static void fetchLocalView(String picPath, ImageView imageView) {
		File filePath = new File(Global.SHOPPING_PICTURES_DIRECTORY, picPath);
		if (filePath.exists() && filePath.length() > 0) {
			imageView.setImageBitmap(BitmapFactory.decodeFile(filePath
					.getAbsolutePath()));
			return;
		}
	}

	public static void fetchView(String picUrl, final ImageView imageView,
			boolean useExisting, int sampleSize) {

		String picPath = Global.getPicPath(picUrl);
		if (useExisting) {
			File filePath = new File(picPath);
			if (filePath.exists() && filePath.length() > 0) {
				imageView.setImageBitmap(BitmapFactory.decodeFile(picPath));
				return;
			}
		}

		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message message) {
				Bitmap bmp = (Bitmap) message.obj;
				imageView.setImageBitmap(bmp);
			}
		};

		sendMessage(handler, picUrl, picPath, sampleSize);
	}

	public static void fetchView(String picUrl, final View view,
			boolean useExisting, int sampleSize) {
		String picPath = Global.getPicPath(picUrl);
		if (useExisting && (new File(picPath)).exists()) {
			BitmapDrawable drw = new BitmapDrawable(picPath);
			view.setBackgroundDrawable(drw);
			return;
		}

		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message message) {
				Bitmap bmp = (Bitmap) message.obj;
				view.setBackgroundDrawable(new BitmapDrawable(bmp));
			}
		};

		sendMessage(handler, picUrl, picPath, sampleSize);
	}

	private static void sendMessage(final Handler handler, final String picUrl,
			final String picPath, final int sampleSize) {
		Thread thread = new Thread() {
			@Override
			public void run() {
				Bitmap drawable = fetchDrawable(picUrl, picPath, sampleSize);
				Message message = handler.obtainMessage(1, drawable);
				handler.sendMessage(message);
			}
		};
		thread.start();
	}

	private static Bitmap fetchDrawable(String picUrl, final String picPath,
			int sampleSize) {
		try {
			InputStream is = fetch(picUrl);
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = sampleSize;
			options.inDither = true;
			options.inScaled = true;
			BufferedInputStream bis = new BufferedInputStream(is);
			Bitmap bitmap = BitmapFactory.decodeStream(bis);
			// new Rect(0, 0, 0, 0), options);
			saveToFile(bitmap, picPath);
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private static void saveToFile(final Bitmap bitmap, final String path) {
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				FileOutputStream out = null;
				try {
					out = new FileOutputStream(path);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
					out.close();
				} catch (Exception e) {
					e.printStackTrace();
					if (out != null)
						try {
							out.close();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
				}
			}
		});
		thread.start();
	}

	private static InputStream fetch(String picUrl) {
		Socket socket = null;
		ObjectOutputStream dos = null;
		try {
			socket = new Socket(Global.SERVER_IMAGE_IP, Global.IMAGE_GET_PORT);

			// send name
			dos = new ObjectOutputStream(socket.getOutputStream());
			dos.writeObject(picUrl);

			// read pic
			return new DataInputStream(socket.getInputStream());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}